﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Linq.Expressions;
using System.Data.Objects;
using System.Data.Metadata.Edm;
using System.Data.SqlClient;

namespace EBA.Data
{
    public static class ObjectSetEx
    {
        //public static int Delete<TEntity>(this Table<TEntity> table, Expression<Func<TEntity, bool>> predicate)
        //    where TEntity : class
        //{
        //    string tableName = table.Context.Mapping.GetTable(typeof(TEntity)).TableName;
        //    string command = String.Format("DELETE FROM {0}", tableName);

        //    ConditionBuilder conditionBuilder = new ConditionBuilder();
        //    conditionBuilder.Build(predicate.Body);

        //    if (!String.IsNullOrEmpty(conditionBuilder.Condition))
        //    {
        //        command += " WHERE " + conditionBuilder.Condition;
        //    }

        //    return table.Context.ExecuteCommand(command, conditionBuilder.Arguments);
        //}

        public static int DeleteAll<TEntity>(this ObjectSet<TEntity> table, Expression<Func<TEntity, bool>> predicate)
        where TEntity : class
        {
            string tableName = table.GetTableName();

            var query = ((ObjectQuery)table.Where(predicate));

            string select = query.ToTraceString();

            var entitySetName = table.Context.DefaultContainerName + "." + table.EntitySet.Name;

            string equals = string.Join(" and ",table.EntitySet.ElementType.KeyMembers.Select(i=>string.Format("eba1.{0} = eba2.{0}",i.Name)));

            string command = String.Format("DELETE FROM [{0}] FROM [{0}] as eba1 join ({1}) as eba2 on ({2})", tableName,select,equals);
            var parameters = query.Parameters.Select(i => new SqlParameter { ParameterName = i.Name, Value=i.Value}).ToArray();
            return table.Context.ExecuteStoreCommand(command, parameters);

            
        }

        //public static int Update<TEntity>(this Table<TEntity> table,
        //    Expression<Func<TEntity, TEntity>> evaluator, Expression<Func<TEntity, bool>> predicate)
        //    where TEntity : class
        //{
        //    return 0;
        //}

        private static string GetTableName<TEntity>(this ObjectSet<TEntity> table) where TEntity : class
        {
            string snippet = "FROM [dbo].[";

            string sql = table.ToTraceString();
            string sqlFirstPart = sql.Substring(sql.IndexOf(snippet) + snippet.Length);
            string tableName = sqlFirstPart.Substring(0, sqlFirstPart.IndexOf("]"));
            return tableName;
        }

    }
}
